package com.example.nextgen.generator;

import cn.hutool.core.util.StrUtil;
import com.example.nextgen.io.FileHandler;
import com.example.nextgen.parser.excel.model.ExcelParserResult;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author martin
 * @date Created in 2022/11/10 22:15
 * @description
 */
@Component
public class Generator {

    @Resource
    FileHandler fileHandler;

    public List<GenerateResult> generation(ExcelParserResult parserResult) {

        List<Sheet> templateSheets = parserResult.getTemplateSheets();
        Map<String, Object> developForms = parserResult.getDevelopForms();
        List<GenerateResult> results = new ArrayList<>();
        for (Sheet templateSheet : templateSheets) {
            String templateContent = fileHandler.readTemplates(null);
            Cell cell = templateSheet.getRow(0).getCell(0);
            if (cell != null){
                templateContent += cell.getStringCellValue();
            }
            if(StrUtil.isBlank(templateContent)){
                continue;
            }
            String gen = freemarkerGen(templateSheet.getSheetName(), templateContent, developForms);
            GenerateResult result = GenerateResult.builder()
                    .excelParserResult(parserResult)
                    .sheetName(templateSheet.getSheetName())
                    .content(gen)
                    .build();
            results.add(result);
        }
        return results;

    }

    public String freemarkerGen(String templateName, String templateContent, Object data){
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_31);
        StringTemplateLoader loader = new StringTemplateLoader();
        loader.putTemplate(templateName,templateContent);
        cfg.setTemplateLoader(loader);
        cfg.setDefaultEncoding(StandardCharsets.UTF_8.displayName());
        try {
            StringWriter writer = new StringWriter();
            cfg.getTemplate(templateName).process(data,writer);
            return writer.toString();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
